package scala.cookbook.akka

/**
  * Created by shichen on 2017/5/10.
  */

import akka.actor.Actor.Receive
import akka.actor._

case class CreateChild(name: String)

case class Name(name: String)

class Child extends Actor {
  var name = "No name"

  override def postStop(): Unit = {
    println(s"$name was killed")
  }

  override def receive: Receive = {
    case Name(name) => this.name = name
    case _ => println(s"Child $name got msg")
  }
}

class Parent extends Actor {
  override def receive: Receive = {
    case CreateChild(name) =>
      println(s"parent about to create child $name")
      val child = context.actorOf(Props[Child], name = s"$name")
      child ! Name(name)
    case _ => println(s"Parent got other msg")
  }
}

object ParnetChildActor extends App {
  val sys = ActorSystem("parentchildactor")
  val parent = sys.actorOf(Props[Parent], name = "parent")
  parent ! CreateChild("Jonathan")
  parent ! CreateChild("Jordan")

  Thread.sleep(500)

  println("sending Jonathan a PoisonPill")
  val jonathan = sys.actorSelection("/user/Parent/Jonathan")
  jonathan ! PoisonPill

  Thread.sleep(2000)
  sys.shutdown()
}
